package cn.com.flever.utils;

import cn.com.flever.action.AutoDeployAction;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.filters.TextConsoleBuilder;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectCoreUtil;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 　* @Description: TODO
 * 　* @author qiyu
 * 　* @date 2021/4/8 11:21
 *
 */
public class ConsoleUtils {

    public static ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(3,10,5, TimeUnit.MINUTES,new ArrayBlockingQueue(200));

    public  ConsoleView consoleView;

    public ConsoleUtils(Project project) {
        TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(ProjectCoreUtil.theProject);
        builder.setViewer(true);
        consoleView = builder.getConsole();
        JPanel panel = new JPanel(new BorderLayout());
        DefaultActionGroup toolbarActions = new DefaultActionGroup();
        ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, toolbarActions, false);
        panel.add(actionToolbar.getComponent(), BorderLayout.WEST);
        panel.add(consoleView.getComponent(), BorderLayout.CENTER);
        actionToolbar.setTargetComponent(panel);
        toolbarActions.addAll(consoleView.createConsoleActions());
        toolbarActions.addAction(new AutoDeployAction());
        panel.updateUI();
        final RunContentDescriptor contentDescriptor = new RunContentDescriptor(consoleView, null, panel, "FJCode");
        ExecutionManager.getInstance(ProjectCoreUtil.theProject).getContentManager()
                .showRunContent(DefaultRunExecutor.getRunExecutorInstance(), contentDescriptor);
    }


    public  void print(String text)
    {
        poolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                consoleView.print(text+"\n", ConsoleViewContentType.NORMAL_OUTPUT);
            }
        });

    }

    public  void print(String text,ConsoleViewContentType type)
    {
        poolExecutor.submit(new Runnable() {
            @Override
            public void run() {
                consoleView.print(text+"\n", type);
            }
        });
    }

}
